//
//  MessageListTableViewController.m
//  group14
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 吕志伟. All rights reserved.
//

#import "MessageListTableViewController.h"
#import "MessageListTableViewCell.h"
#import "ChatViewController.h"
#import "SpeakOthers.h"

#define kChatSql [ChatRecordSql shareChatRecordSql]
@interface MessageListTableViewController ()<AVIMClientDelegate,UITabBarDelegate>

@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) NSMutableArray *lastChatMessageArray;

@property (nonatomic, strong) AVIMClient *client;

@property (nonatomic, assign) NSInteger intger;

@property (nonatomic, copy) NSString *idStr;

@end

@implementation MessageListTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.client = [[AVIMClient alloc] init];
    
    // 设置 client 的 delegate，并实现 delegate 方法
    self.client.delegate = self;
    
    AVUser *user = [AVUser currentUser];
    
    // Jerry 用自己的名字作为 ClientId 打开了 client
    [self.client openWithClientId:user.username callback:^(BOOL succeeded, NSError *error) {
        // ...
    }];
    
}

- (void)conversation:(AVIMConversation *)conversation didReceiveTypedMessage:(AVIMTypedMessage *)message {
    
    NSLog(@"收到的消息%@", message.text);
    
    //通知中心传值
    NSDictionary *dic = [NSDictionary dictionaryWithObject:message forKey:@"MessageKey"];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"message" object:nil userInfo:dic];
    
    AVUser *user = [AVUser currentUser];
    
    AVQuery *query = [AVQuery queryWithClassName:@"_Conversation"];
    
    NSString *creatStr = [NSString stringWithFormat:@"%@and%@",user.username,message.clientId];
    
    [query whereKey:@"name" equalTo:creatStr];
    
    [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
        
        _idStr = [object objectForKey:@"objectId"];
        
        if(!object)
        {
                // Tom 建立了与 Jerry 的会话
            [self.client createConversationWithName:creatStr clientIds:@[message.clientId] callback:^(AVIMConversation *conversation, NSError *error)
                {
            
                    [self viewWillAppear:YES];
            }];
        }
        else
        {
            
            // Tom 用自己的名字作为 ClientId 打开 client
            
                // Tom 查询 id 为 551260efe4b01608686c3e0f 的会话
                AVIMConversationQuery *query = [self.client conversationQuery];
                [query getConversationById:_idStr callback:^(AVIMConversation *conversation, NSError *error) {
                    
                    [self viewWillAppear:YES];
                }];
        }
        
        
    }];
    
    //tabbar小红点
    self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",_intger];
    
}

- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController
{
    viewController.tabBarItem.badgeValue = nil;
    
    _intger = 1;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    AVUser *user = [AVUser currentUser];
    
    [self.client openWithClientId:user.username callback:^(BOOL succeeded, NSError *error) {
        
        [self findRecentConverSationsAndUserName:user.username WithBlock:^(NSArray *objects, NSError *error) {
            
            _lastChatMessageArray = [NSMutableArray array];
            
            _dataArray = [NSMutableArray arrayWithArray:objects];
            
            NSLog(@"1====%@",objects);
            
            for (AVObject *object in _dataArray) {
                
                NSString *conversationId = [object objectForKey:@"objectId"];
                
                NSLog(@"+++++");
                
                [self getLastMessagesFromCacheWithLimit:1 conversationId:conversationId];
            }
            
            [self.tableView reloadData];
            
        }];
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取最近聊天列表
- (void)findRecentConverSationsAndUserName:(NSString *)userName WithBlock:(AVIMArrayResultBlock)block
{
    AVQuery *query = [AVQuery queryWithClassName:@"_Conversation"];

    [query whereKey:@"c" equalTo:userName];
    [query whereKey:kAVIMKeyMember containedIn:@[self.client.clientId]];
    query.limit = 100;
    [query orderByDescending:@"updatedAt"];
    [query findObjectsInBackgroundWithBlock:block];
}

//获取最后一句聊天
- (void)getLastMessagesFromCacheWithLimit:(NSUInteger)limit conversationId:(NSString *)conversationId
{
    
    AVIMConversationQuery *query = [self.client conversationQuery];
    
    [query getConversationById:conversationId callback:^(AVIMConversation *conversation, NSError *error) {
        // 查询对话中最后 10 条消息
        [conversation queryMessagesWithLimit:limit callback:^(NSArray *objects, NSError *error) {
            
            NSLog(@"%@",objects);
            
            if ([objects  isEqual: @[]]) {
                
                AVIMTextMessage *message = [AVIMTextMessage messageWithText:@"" attributes:nil];
                
                [_lastChatMessageArray addObject:message];
                
            }else
            {
                AVIMTypedMessage *message = [objects lastObject];
                
                [_lastChatMessageArray addObject:message];
                
                [self.tableView reloadData];
            }
        }];
    }];

    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return _lastChatMessageArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UIStoryboard *board=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    
    ChatViewController *chat =[board instantiateViewControllerWithIdentifier:@"ChatViewController"];
    
    chat.hidesBottomBarWhenPushed = YES;
    
    AVObject *UserNameObject = _dataArray[indexPath.row];
    
    NSString *userName = [UserNameObject objectForKey:@"name"];
    
    NSArray *arry=[userName componentsSeparatedByString:@"and"];
    
    chat.chatName = [arry lastObject];
    
    [self.navigationController pushViewController:chat animated:YES];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MessageListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MessageListCell" forIndexPath:indexPath];
    
    AVObject *UserNameObject = _dataArray[indexPath.row];
    
    NSString *userName = [UserNameObject objectForKey:@"name"];
    
    NSArray *arry=[userName componentsSeparatedByString:@"and"];
    
    cell.nameLabel.text = [arry lastObject];
    
    AVIMTypedMessage *message = _lastChatMessageArray[indexPath.row];
    
    cell.MessageLabel.text = message.text;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Navigation


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

@end
